document.addEventListener('DOMContentLoaded', function () {
    const userId = localStorage.getItem('user_id');
    const token = localStorage.getItem('access_token');

    // 没有 token 或用户 ID 就重定向
    if (!userId || !token) {
        alert('您尚未登录，请重新登录');
        window.location.href = '/';
        return;
    }

    // 请求用户信息
    fetch(`/api/user_info/?user_no=${userId}`, {
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('获取用户信息失败');
        }
        return response.json();
    })
    .then(data => {
        if (data.user_name) {
            const userNameElement = document.querySelector('.header');
            userNameElement.innerHTML = `操作员: ${data.user_name} <a href="#" id="logout">退出系统</a>`;
        } else {
            console.error('未找到 user_name');
        }
    })
    .catch(error => {
        console.error('错误:', error);
        alert('身份验证失败，请重新登录');
        localStorage.clear();
        window.location.href = '/';
    });

    document.body.addEventListener('click', function (event) {
        if (event.target && event.target.id === 'logout') {
            event.preventDefault();
            localStorage.clear();
            window.location.href = '/';
        }
    });

    function updateClock() {
        const clock = document.getElementById('clock-display');
        const now = new Date();
        const formattedTime = now.toLocaleString();
        if (clock) {
            clock.textContent = "当前时间：" + formattedTime;
        }
    }
    setInterval(updateClock, 1000);
    updateClock();
});
